# -*- coding: utf-8 -*-
"""
------------------------------------------------------------------------------
    File Name:  data2json
    Author   :  wanwei1029
    Date     :  2018/10/9
    Desc     : 此类主要用于将解析出来的内容以json的格式保存在硬盘上
------------------------------------------------------------------------------
"""
import os
import json
import samp.spider.aikantxt.spider_utils as utils


class DataToJson(object):
    def __init__(self):
        self.basePath = utils.SAVE_DIR

    def process_data(self, item):
        if item['book_name']:
            book_path = self.basePath + "\\" + utils.rem_special_char(item['book_name'])
            if not os.path.exists(book_path):
                os.makedirs(book_path)
            # item['title'] = item['title'].replace("底", "第")
            title_replace = utils.rem_special_char(item['title'])
            file_name = book_path + "\\" + title_replace + ".json"
            with open(file_name, "w+", encoding="utf-8") as f:
                json.dump(dict(item), f, ensure_ascii=False, indent=2)
        else:
            print(" book_name is miss. skip...")


def demo():
    """
    """
    item = dict()
    item['book_name'] = "书名"
    item['title'] = "标题"
    item['author'] = "作者"
    item['url'] = "https://www.aikantxt.la/aikan18681/12452994.html"
    item['category'] = "都市小说"
    item['content'] = "内容"
    data2json = DataToJson()
    data2json.process_data(item)


if __name__ == '__main__':
    test_method = "rem_special_char"
    if test_method == "demo":
        demo()
